package com.view;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;

import com.android.ddmlib.AndroidDebugBridge;
import com.android.ddmlib.IDevice;
import com.android.ddmlib.RawImage;
import com.util.Sunswing;


public class MainWindow extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4575932146837325427L;
	private JPanel corePanel, centerPanel, westPanel, devicePanel, infoPanel;
	private JImagePanel imgPanel;
	private JButton refreshBtn;
	private JMenuBar menuBar;
	private JMenu settings;
	private JScrollPane itemPanel;
	private static IDevice[] devices;
	public static IDevice device;
	private JList<String> jlist;
	private static DefaultListModel<String> listModel;
	private Thread thread;
	private AndroidDebugBridge bridge;
	private String targetName;

	public static void main(String[] args) {
		new MainWindow();
	}

	public MainWindow() {
		super();
		/* 设置窗体样式 */
		Sunswing.setWindowStyle('0');
		/* 加载窗体 */
		initWindow();
		/* 加载设备 */
		initMobiles();
		/* 加载事件 */
		addActionListener();
	}

	private void initWindow() {
		getContentPane().setLayout(new BorderLayout(0, 0));

		corePanel = new JPanel();
		corePanel.setFocusable(true);
		getContentPane().add(corePanel, BorderLayout.CENTER);
		corePanel.setLayout(new BorderLayout(0, 0));

		westPanel = new JPanel();
		corePanel.add(westPanel, BorderLayout.WEST);
		westPanel.setLayout(new GridLayout(2, 1));

		devicePanel = new JPanel();
		devicePanel.setBorder(BorderFactory.createTitledBorder("设备列表"));
		westPanel.add(devicePanel);
		devicePanel.setLayout(new BorderLayout(0, 0));

		refreshBtn = new JButton("Refresh");
		devicePanel.add(refreshBtn, BorderLayout.SOUTH);

		itemPanel = new JScrollPane();
		itemPanel.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		itemPanel.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		devicePanel.add(itemPanel, BorderLayout.CENTER);

		listModel = new DefaultListModel<>();
		jlist = new JList<>(listModel);
		itemPanel.setViewportView(jlist);

		infoPanel = new JPanel();
		infoPanel.setBorder(BorderFactory.createTitledBorder("设备信息"));
		westPanel.add(infoPanel);

		centerPanel = new JPanel();
		centerPanel.setBorder(BorderFactory.createTitledBorder("设备实时画面"));
		corePanel.add(centerPanel, BorderLayout.CENTER);
		centerPanel.setLayout(new BorderLayout(0, 0));

		imgPanel = new JImagePanel();
		centerPanel.add(imgPanel);

		menuBar = new JMenuBar();
		setJMenuBar(menuBar);

		settings = new JMenu("Settings");
		menuBar.add(settings);

		pack();
		setMinimumSize(new Dimension(800, 600));
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Sunswing.setWindowCenter(this);
		setVisible(true);
	}

	private void initMobiles() {
		String adbLocation = null;
		String androidHome = System.getenv("ANDROID_HOME");
		if (androidHome != null && androidHome.length() > 0) {
			adbLocation = androidHome + File.separator + "platform-tools" + File.separator + "adb.exe";
		} else {
			System.err.println("Please confirm your ANDROID_HOME!");
		}
		AndroidDebugBridge.init(false);
		bridge = AndroidDebugBridge.createBridge(adbLocation, true);
		int count = 0;
		while (bridge.hasInitialDeviceList() == false) {
			try {
				Thread.sleep(1000);
				count++;
			} catch (InterruptedException e) {

			}
			if (count > 5) {
				System.err.println("Timeout getting device list!");
				return;
			}
		}
		devices = bridge.getDevices();
		for (IDevice iDevice : devices) {
			listModel.addElement(iDevice.getName());
			System.out.println(iDevice.getName());
		}

		// you can also see some information about validate method
		this.validate();
		thread = new Thread(new Runnable() {

			@Override
			public void run() {
				while (true) {
					imgPanel.setWidth(centerPanel.getWidth());
					imgPanel.setHight(centerPanel.getHeight());
					imgPanel.setBackgroundImage(getImageIcon(targetName).getImage());
				}
			}
		});

	}

	private void addActionListener() {

		refreshBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				getContentPane().validate();
				
			}
		});

		/**
		 * 点击设备列表项触发事件
		 */
		jlist.addMouseListener(new MouseListener() {

			@Override
			public void mouseReleased(MouseEvent e) {

			}

			@Override
			public void mousePressed(MouseEvent e) {

			}

			@Override
			public void mouseExited(MouseEvent e) {

			}

			@Override
			public void mouseEntered(MouseEvent e) {

			}

			@Override
			public void mouseClicked(MouseEvent e) {
				targetName = (String) ((JList<?>) e.getSource()).getSelectedValue();
				targetName = targetName.substring(targetName.lastIndexOf("-") + 1);
				for (IDevice iDevice : devices) {
					if (iDevice.getSerialNumber().equals(targetName)) {
						device = iDevice;
						if (!thread.isAlive())
							thread.start();
					}
				}
			}
		});
	}

	private ImageIcon getImageIcon(String targetNum) {
		try {
			// long start = System.currentTimeMillis();
			RawImage rawImage = device.getScreenshot();
			// long end = System.currentTimeMillis();
			// System.out.println("获取屏幕时间：" + (end - start) + "-毫秒");
			BufferedImage image = new BufferedImage(rawImage.width, rawImage.height, BufferedImage.TYPE_INT_RGB);
			int index = 0;
			int IndexInc = rawImage.bpp >> 3;
			for (int y = 0; y < rawImage.height; y++) {
				for (int x = 0; x < rawImage.width; x++) {
					int value = rawImage.getARGB(index);
					index += IndexInc;
					image.setRGB(x, y, value);
				}
			}
			return new ImageIcon(image);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
